/**
 * jquery.wtFormDirty.js v1.0.0
 * 
 * @author Yasar Bayar <yasarbayar@gmail.com>
 */

(function($) {
	$.fn.wtFormDirty = function(options){
		options = $.extend({},{
			onFormDirty:function(){},
			onFormClean:function(){}
		},options);
		
		var $FORM = $(this);

		$FORM.find('input,select,texetarea').each(function(){
			var $el=$(this);
			$el.change(function(){
				$FORM.data('dirty',(isElementModified($el.get(0)))?true:false);
				if($FORM.data('dirty')) options.onFormDirty();
				else options.onFormClean();
			});
			$el.blur(function(){$el.change();});
		});
		
		var isFormModified = function(oForm)
		{
			var el, opt, hasDefault, i = 0, j;
			while (el = oForm.elements[i++]) {
				if(isElementModified(el)) return true;
			}
			return false;
		};
		
		var isElementModified = function(el){
			switch (el.type) {
				case 'text' :
	                   	case 'textarea' :
	                   	case 'hidden' :
	                         	if (!/^\s*$/.test(el.value) && el.value != el.defaultValue) return true;
	                         	break;
	                   	case 'checkbox' :
	                   	case 'radio' :
	                         	if (el.checked != el.defaultChecked) return true;
	                         	break;
	                   	case 'select-one' :
	                   	case 'select-multiple' :
	                         	j = 0, hasDefault = false;
	                         	while (opt = el.options[j++])
	                                	if (opt.defaultSelected) hasDefault = true;
	                         	j = hasDefault ? 0 : 1;
	                         	while (opt = el.options[j++]) 
	                                	if (opt.selected != opt.defaultSelected) return true;
	                         	break;
			}
			return false;
		};
	};
})(jQuery);